package cn.tedu.coolshark.controller;

import cn.tedu.coolshark.entity.Product;
import cn.tedu.coolshark.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.Date;
import java.util.List;

@RestController
public class ProductController {
    // @Value注解这种写法是找到配置文件中的值读取出来给 dirPath变量
    @Value("${dirPath}")
    private String dirPath;//dirPath非固定名 可以随意 通过注解赋值

    @Autowired
    ProductMapper mapper;

    @RequestMapping("/product/insert")
    public void insert(@RequestBody Product product){
        product.setCreated(new Date());
        mapper.insertById(product);
    }

    @RequestMapping("/product/select/index")
    public List<Product> selectIndex(Product product){
        product.setCreated(new Date());
        return mapper.selectIndex(product);
    }

    @RequestMapping("/product/select")
    public List<Product> select(){
        return mapper.select();
    }

    @RequestMapping("/product/delete")
    public void delete(int id){
        //通过id获取本地图片路径
        String url =  mapper.selectUrlById(id);
        String filePath =dirPath+"/"+url;
        new File(filePath).delete();
        //删除数据库数据
        mapper.delete(id);
    }

    @RequestMapping("/product/select/top")
    public List<Product> SelectTop(){
        List<Product> list =mapper.selectTop();
        for(Product p : list){
            if(p.getTitle().length()>4){
                String title = p.getTitle().substring(0,3)+"....";
                p.setTitle(title);
            }
        }
        return list;
    }

    @RequestMapping("/product/select/category")
    public List<Product> SelectCategory(int cid){
        return mapper.SelectCategory(cid);
    }

    @RequestMapping("/search")
    public List<Product> selectByWd(String wd){

        System.out.println("wd="+wd);
        return mapper.selectByWd(wd);
    }
    @RequestMapping("/product/selectById")
    public Product selectById(int id){
        mapper.updateViewCount(id);
        return mapper.selectById(id);
    }
}
